import matplotlib.pyplot as plt
import time

import datetime as dt
import easyquotation


import json,requests,datetime;    


import pandas as pd  #







plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def update(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

















str1 = "2022-08-18 09:00:00"
str2 = "2022-08-18 09:01:00"

dt1 = dt.datetime.strptime(str1, '%Y-%m-%d %H:%M:%S')
dt2 = dt.datetime.strptime(str2, '%Y-%m-%d %H:%M:%S')

dt3  = dt2 -dt1


class FlowManager:
    def __init__(self):
        self.x = 20
        self.step = 20
        self.update = 1
        self.count = 0
        self.time = dt.datetime.now()

    def foward(self):
        self.x = self.x + self.step
        self.update = 0
        self.count = 0

    def valid_time(self, time):
        diff = time - self.time
        diff_test = int((self.time - time).seconds/60)
        diff_min = int( diff.seconds/60);
        if diff_min >= 5:
            return True
        else:
            return False


class FlowBook:
    def __init__(self):
        self.lastPx = 0
        self.ask = 0
        self.bid = 0
        self.ask_vol = 0
        self.bid_vol = 0
        self.trade_vol = 0
        self.price_up = 0
        self.price_down = 0

class Market:
    def _init__(self):
        self.lastPx = 0
        self.ask1 = 0
        self.bid1 = 0
        self.ask_vol1 = 0
        self.bid_vol1 = 0
        self.trade_vol = 0
        self.open_price = 0
        self.time = dt.datetime.now()




def process_market(market, flow_manager, flowbook):

    if ( flow_manager.valid_time(market.time) == False):
        return 

    if flowbook.lastPx == 0:
        flowbook.lastPx = market.lastPx
        flowbook.ask =market.ask1
        flowbook.ask_vol = market.ask_vol1
        flowbook.bid = market.bid1
        flowbook.bid_vol = market.bid_vol1
        flowbook.trade_vol = market.trade_vol
        return

    px = 0
    left = 0 
    right = 0
    if flowbook.lastPx == market.lastPx:
        return 
    if flowbook.lastPx < market.lastPx:  #主买
        px, left, right = update_flow( market.trade_px, market.trade_vol, 1 ,flowbook)
    else:
    
        px, left, right = update_flow( market.trade_px, market.trade_vol, 0, flowbook)
    update_flow_book(market.lastPx, market.ask1, market.ask_vol1, market.bid1, market.bid_vol1, market.trade_vol, flowbook)
    y =  px / (flowbook.price_up - flowbook.price_down) * 100



#'{"600000": {"name": "浦发银行", "open": 7.27, "close": 7.28, "now": 7.21, "high": 7.27, "low": 7.19, "buy": 7.21, "sell": 7.22, "turnover": 12991819, "volume": 93820911.0, "bid1_volume": 23200, "bid1": 7.21, "bid2_volume": 733994, "bid2": 7.2, "bid3_volume": 771200, "bid3": 7.19, "bid4_volume": 500400, "bid4": 7.18, "bid5_volume": 223000, "bid5": 7.17, "ask1_volume": 271010, "ask1": 7.22, "ask2_volume": 658214, "ask2": 7.23, 
#"ask3_volume": 261600, "ask3": 7.24, "ask4_volume": 193500, "ask4": 7.25, "ask5_volume": 111400, "ask5": 7.26, "date": "2022-08-18", "time": "15:00:00"}}'
def recv_market():
    quotation = easyquotation.use('sina')
    flow_manager = FlowManager()
    flow_book = FlowBook()
    while(True):
        market = str(quotation.real('sh600000')) # 新浪 ['sina'] 腾讯 ['tencent', 'qq'] 
        print(market)
        market = market.replace("'", '"')
        market_json = json.loads(market)
        
        msg = Market()
        msg.lastPx     =  market_json["600000"]["now"]
        msg.ask1       =  market_json["600000"]["ask1"]
        msg.bid1       =  market_json["600000"]["bid1"]
        msg.ask_vol1   =  market_json["600000"]["ask1_volume"]
        msg.bid_vol1   =  market_json["600000"]["bid1_volume"]
        msg.trade_vol  =  market_json["600000"]["turnover"]
        msg.open_price =  market_json["600000"]["open"]
        
        datetime_str = market_json["600000"]["date"]+" "+ market_json["600000"]["time"]
        datetime_object = dt.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        msg.time       =  datetime_object

        process_market(msg, flow_manager, flow_book)

        


#recv_market()



def update_flow_book(px,ask, ask_vol, bid, bid_vol, trade_vol ,flowbook):
    flowbook.lastPx = px
    flowbook.ask = ask
    flowbook.ask_vol = ask_vol
    flowbook.bid = bid
    flowbook.bid_vol = bid_vol
    flowbook.trade_vol = flowbook.trade_vol + trade_vol


def update_flow(trade_px, trade_vol, side, flowbook):
    left = 0
    right = 0
    if side == 1: # 主买
        left = flowbook.ask
        right = trade_vol - flowbook.ask
    else:
        left = trade_vol - flowbook.bid
        right = flowbook.bid
    return {trade_px, left, right}








x = list(range(0,100))
y = list(range(0,100))
#plt.plot(x, y, "o", color="black")
plt.xlabel('x')
plt.ylabel('y')
plt.xlim([0, 1000])
plt.ylim([0, 100])
#for i, (x, y) in enumerate(zip(x, y)):
#    plt.text(x, y, i+1, color="red", fontsize=12)
#plt.title('graph!')
#plt.show()





def add_flow(y, left, right,trade_vol):
    plt.text(20 - 2, y,left ,color="green", fontsize=5)
    plt.text(20 + 2, y,right ,color="red", fontsize=5)
    #plt.show()
    #plt.draw()



for i in range(10,20):
    time.sleep(2)
    add_flow(i+ 5 , 30 ,40 , 300)
    plt.draw()
#plt.show()